﻿using AutoMapper;
using BaseData.API.Write.Applications.Commands;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace BaseData.API.Write.Applications.CommandHandlers
{
    /// <summary>
    /// 修改角色--配置权限 请求
    /// </summary>
    public class UpdRoleCommandHandler : IRequestHandler<UpdRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<RolePermissionRelation> rolePermissionRep;
        private readonly IBaseRepository<Permission> permissionRep;
        private readonly IMapper mapper;
        private readonly ILogger<UpdRoleCommandHandler> logger;

        public UpdRoleCommandHandler(IBaseRepository<Role> roleRep,
            IBaseRepository<RolePermissionRelation> rolePermissionRep,
            IBaseRepository<Permission> permissionRep,IMapper mapper,
            ILogger<UpdRoleCommandHandler> logger)
        {
            this.roleRep = roleRep;
            this.rolePermissionRep = rolePermissionRep;
            this.permissionRep = permissionRep;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(UpdRoleCommand request, CancellationToken cancellationToken)
        {
            var count = await roleRep.GetAll().CountAsync(x => x.RoleId != request.RoleId && x.RoleName == request.RoleName);
            if (count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.添加失败,
                    Message = "该角色已存在!!!",
                    Data = -1
                };
            }

            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.修改成功;
            result.Message=ApiEnum.修改成功.ToString();

            using (var tran = roleRep.DB.Database.BeginTransaction()) 
            {
                try
                {
                    var roles = mapper.Map<Role>(request);
                    roles.CreateTime = DateTime.Now;
                    await roleRep.UpdateAsync(roles);

                    var listSelect = rolePermissionRep.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
                    await rolePermissionRep.DeleteRange(listSelect);
                    var list = new List<RolePermissionRelation>();
                    foreach (var item in request.PermissionIds)
                    {
                        list.Add(new RolePermissionRelation()
                        {
                            RoleId = request.RoleId,
                             PermissionId= item
                        });
                    }
                    await rolePermissionRep.AddRange(list);

                    tran.Commit();
                }
                catch (Exception ex)
                {
                    logger.LogError("=>" + ex.Message);
                    result.Code = ApiEnum.修改失败;
                    result.Message = ApiEnum.修改失败.ToString()+ex.Message;
                    tran.Rollback();
                }
            }

            return await Task.FromResult(result);
        }
    }
}
